﻿using System.Linq;
using System.Web.Security;
using VideoSeller.Business.Data;
using MembershipUser = VideoSeller.Business.Data.MembershipUser;

namespace VideoSeller.Business.Models
{
	public class MembershipUserModel : Repository<MembershipUser>
	{
		private readonly MailModel _mailModel;

		public MembershipUserModel(MailModel mailModel)
		{
			_mailModel = mailModel;
		}

		public MembershipUser GetMembershipUser(string login)
		{
			return Table.SingleOrDefault(x => x.UserName == login);
		}

		public string ResetPassword(string email)
		{
			var userName = Membership.GetUserNameByEmail(email);

			if (string.IsNullOrEmpty(userName))
			{
				return string.Empty;
			}

			var membershipUser = Membership.GetUser(userName);

			if (membershipUser != null)
			{
                if (membershipUser.IsLockedOut) membershipUser.UnlockUser();// HPN modify at 23.09.13

				var newPassword = membershipUser.ResetPassword();
				Membership.UpdateUser(membershipUser);
				_mailModel.SendResetPasswordConfirmation(userName, email, newPassword);
				return newPassword;
			}

			return string.Empty;
		}
	}
}